﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// 
    /// </summary>
    public class SkinDetectionFilter : MacroFilter, IBaseForeBackgroundColorFilter
    {
        protected static Color m_ForegroundColor = Definitions.White;
        protected static Color m_BackgroundColor = Definitions.Black;

        protected RoundColors m_RoundColors = new RoundColors(180);
        protected ChannelDifferences m_ChannelDifferences = new ChannelDifferences();

        /// <summary>
        /// Gets or sets the color of the background.
        /// </summary>
        /// <value>The color of the background.</value>
        public Color BackgroundColor
        {
            get { return m_BackgroundColor; }
            set { m_BackgroundColor = value; }
        }

        /// <summary>
        /// Gets or sets the foreground.
        /// </summary>
        /// <value>The foreground.</value>
        public Color Foreground
        {
            get { return m_ForegroundColor; }
            set { m_ForegroundColor = value; ; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmapClonedRoundColors = (UnsafeBitmap)_bitmap.Clone();
            m_RoundColors.Execute(bitmapClonedRoundColors);
            UnsafeBitmap bitmapClonedBaseColorSegmentation = (UnsafeBitmap)_bitmap.Clone();
            new BaseColorSegmentation().Execute(bitmapClonedBaseColorSegmentation);
            UnsafeBitmap bitmapMask = (UnsafeBitmap)_bitmap.Clone();
            int nWidth = _bitmap.Width;
            int nHeigh = _bitmap.Height;
            int x = 0;
            int y = 0;
            for (y = 0; y < nHeigh; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    bitmapMask.SetPixel(x, y, Math.Abs(bitmapClonedRoundColors.GetPixel(x, y).R - bitmapClonedBaseColorSegmentation.GetPixel(x, y).R) < 20 ? m_ForegroundColor : m_BackgroundColor);
                }
            }
            new ChannelDifferences().ExecutedMasked(_bitmap, bitmapMask);
            return _bitmap;
        }
    }
}
